package pt.mauromad.guias.controller;

import static java.lang.String.format;
import static pt.mauromad.guias.utils.transformation.Transformations.Address2Dao;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import pt.mauromad.guias.bean.AddressBean;
import pt.mauromad.guias.dao.AddressDao;
import pt.mauromad.guias.dao.CompanyDao;
import pt.mauromad.guias.utils.form.Action;

@Controller
@RequestMapping("/company/{company:[0-9]+}/address")
public class AddressController extends BaseController {
	@RequestMapping(value = "/new", method = RequestMethod.GET)
	public String create(Model model) {
		model.addAttribute("editable", true);
		add(model, Action.createPost("save"));
		return "address-form";
	}

	@RequestMapping(value = "/new", method = RequestMethod.POST, params = "action=save")
	public String createAddress(@PathVariable CompanyDao company, @Validated AddressBean address) {
		AddressDao dao = Address2Dao.get(address);
		dao.setCompany(company);
		addressService.save(dao);
		return format("redirect:/company/%s", company.getId());
	}

	@RequestMapping(value = "/{address:[0-9]+}", method = RequestMethod.POST, params = "action=default")
	public String setAddressDefault(@PathVariable CompanyDao company, @PathVariable AddressDao address) {
		if (address.getCompany().getId().equals(company.getId())) {
			company.setMainAddress(address);
			companyService.save(company);
		}
		return format("redirect:/company/%s", company.getId());
	}

	@RequestMapping(value = "/{address:[0-9]+}", method = RequestMethod.POST, params = "action=manage")
	public String manage(Model model, @PathVariable Long company, @PathVariable AddressDao address) {
		if (!address.getCompany().getId().equals(company)) {
			return format("redirect:/company/%s", company);
		}

		model.addAttribute("editable", true);
		model.addAttribute("address", address);
		add(model, Action.createPost("manage.save"));
		return "address-form";
	}

	@RequestMapping(value = "/{address:[0-9]+}", method = RequestMethod.POST, params = "action=manage.save")
	public String manage(Model model, @PathVariable CompanyDao company, @PathVariable Long address, @Validated AddressBean addr) {
		addr.setId(address);
		addr.setCompany(company);
		addressService.save(Address2Dao.get(addr));
		return format("redirect:/company/%s", company.getId());
	}
}
